package com.epro.dx.activity.myaddress;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;

import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.activity.ChangeCountryActivity;
import com.epro.dx.activity.RegisterActivity;
import com.epro.dx.activity.forgetpassword.ForgetPasswordSuccessActivity;
import com.epro.dx.activity.order.EditOrderActivity;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.MapUtil;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.AddressModel;
import com.weipu.common.facade.model.AddressModel.Address;
import com.weipu.common.facade.model.CountryModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.GlobalConfig;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

public class EditAddressActivity extends BaseFragmentActivity implements
		OnClickListener {
	private static final String TAG = "EditAddressActivity";
	private EditText firstNameEt, lastNameEt, street1Et,street2Et, cityEt, stateEt,
			countryEt, mobileEt, phoneEt, postalCodeEt;

	private String firstName, lastName, street1,street2, city, state, country, mobile,
			phone, postalCode;

	private Button saveBtn;

	private AddressModel editAddressModel;

	private AddressModel addAddressModel = new AddressModel();

	private String fromType;

	/**
	 * 国家码
	 */
	private CountryModel countryModel;

	/**
	 * 国家列表
	 */
	private ArrayList<String> listCountry;
	
	private int editPosition=-1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Tracker tracker = DXApplication.getContext().getTracker(TrackerName.APP_TRACKER);
		tracker.setScreenName(EditAddressActivity.class.getSimpleName());
		tracker.send(new HitBuilders.ScreenViewBuilder().build());
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_edit_address);
		setTitleContent(R.string.address_add_title);
		setLeftBtnContent(true, -1);
		getExtrasData(getIntent());
		intView();
		setListenner();
		if ("editAddress".equals(fromType)) {
			setTitleContent(R.string.address_change_title);
			setDataToView();
		}
	}

	/**
	 * 编辑地址时 显示老地址在View上
	 */
	private void setDataToView() {
		AddressModel.Address address = null;
		if (null != editAddressModel) {
			address = editAddressModel.getAddress();
			Logger.i(TAG, "address: " + address.toString());
		}
		if (null != address) {
			firstNameEt.setText(address.getFirstName());
			lastNameEt.setText(address.getLastName());
			street1Et.setText(address.getStreet1());
			street2Et.setText(address.getStreet2());
			cityEt.setText(address.getCity());
			stateEt.setText(address.getState());
			SharedPreferences share = getSharedPreferences("countryData",
					MODE_PRIVATE);
			String str = share.getString(address.getCountryCode() + "",
					address.getCountryCode() + "");
			countryEt.setText(str);
			mobileEt.setText(address.getMobilePhone());
			phoneEt.setText(address.getPhoneNumber());
			postalCodeEt.setText(address.getPostalCode());
		}

	}

	/**
	 * 获取Intent传递数据
	 * 
	 * @param intent
	 */
	private void getExtrasData(Intent intent) {
		if (null != intent) {
			countryModel = (CountryModel) intent
					.getSerializableExtra("countryModel");
			if (null != countryModel) {
				listCountry = (ArrayList<String>) MapUtil
						.getValues(countryModel.getAllCountry());
			}
			fromType = intent.getStringExtra("from");
			Logger.i(TAG, "fromType " + fromType);
			if ("editAddress".equals(fromType)) {
				editAddressModel = (AddressModel) intent
						.getSerializableExtra("editModel");
				editPosition=intent.getIntExtra("position", -1);
			}
		}
	}

	/**
	 * 初始化View
	 */
	private void intView() {
		firstNameEt = (EditText) findViewById(R.id.address_firstname);
		lastNameEt = (EditText) findViewById(R.id.address_lastname);
		street1Et = (EditText) findViewById(R.id.address_street1);
		street2Et = (EditText) findViewById(R.id.address_street2);
		cityEt = (EditText) findViewById(R.id.address_city);
		stateEt = (EditText) findViewById(R.id.address_state);
		countryEt = (EditText) findViewById(R.id.address_country);
		mobileEt = (EditText) findViewById(R.id.address_mobile);
		phoneEt = (EditText) findViewById(R.id.address_phone);
		postalCodeEt = (EditText) findViewById(R.id.address_postal_code);
		saveBtn = (Button) findViewById(R.id.address_save_btn);
	}

	/**
	 * 事件监听注册
	 */
	private void setListenner() {
		saveBtn.setOnClickListener(this);
		countryEt.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.address_save_btn:
			if (checkAddress()) {
				AsyncTaskUtil.executeTask(new AddOrEditAddress());
			}
			break;
		case R.id.address_country:
			Bundle bundle = new Bundle();
			bundle.putStringArrayList("listCountry", listCountry);
			Intent intent = new Intent(this, ChangeCountryActivity.class);
			intent.putExtras(bundle);
			startActivityForResult(intent,
					ServerConstant.Parameter.CHANGE_COUNTRY_REQUESTCODE);
			break;

		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == ServerConstant.Parameter.CHANGE_COUNTRY_RESULTCODE) {
			countryEt.setText(data.getStringExtra("countryName"));
			if(null==countryModel){
				countryModel=(CountryModel) data.getSerializableExtra("countryModel");
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private boolean checkAddress() {
		firstName = firstNameEt.getText().toString().trim();
		if (TextUtils.isEmpty(firstName)) {
			AlertToast.alert(EditAddressActivity.this,
					R.string.user_register_title_firstname_null, firstNameEt);
			return false;
		}
		if (!StringUtil.isFirstnameOrLastname(firstName)) {
			AlertToast.alert(EditAddressActivity.this,
					R.string.user_register_title_firstname_format_error,
					firstNameEt);
			return false;
		}
		if (firstName.length() < Constant.Rule.USERNAME_MIN_LENGTH
				|| firstName.length() > Constant.Rule.FIRORLASNAME_MAX_LEN) {
			AlertToast.alert(
					EditAddressActivity.this,
					getString(R.string.user_register_firstname_validate_length,
							Constant.Rule.USERNAME_MIN_LENGTH,
							Constant.Rule.FIRORLASNAME_MAX_LEN), firstNameEt);
			return false;
		}
		// lastname 校验
		lastName = lastNameEt.getText().toString().trim();
		if (TextUtils.isEmpty(lastName)) {
			AlertToast.alert(EditAddressActivity.this,
					R.string.user_register_title_lastname_null, lastNameEt);
			return false;
		}
		if (!StringUtil.isFirstnameOrLastname(lastName)) {
			AlertToast.alert(EditAddressActivity.this,
					R.string.user_register_title_lastname_format_error,
					lastNameEt);
			return false;
		}
		if (lastName.length() < Constant.Rule.USERNAME_MIN_LENGTH
				|| lastName.length() > Constant.Rule.FIRORLASNAME_MAX_LEN) {
			AlertToast.alert(
					EditAddressActivity.this,
					getString(R.string.user_register_lastname_validate_length,
							Constant.Rule.USERNAME_MIN_LENGTH,
							Constant.Rule.FIRORLASNAME_MAX_LEN), lastNameEt);
			return false;
		}

		street1 = street1Et.getText().toString().trim();
		if (TextUtils.isEmpty(street1)) {
			String suggestStr = getResources().getString(
					R.string.user_address_null, " Street1 ");
			AlertToast.alert(EditAddressActivity.this, suggestStr, street1Et);
			return false;
		}
		
		street2 = street2Et.getText().toString().trim();
//		if (TextUtils.isEmpty(street2)) {
//			String suggestStr = getResources().getString(
//					R.string.user_address_null, " Street2 ");
//			AlertToast.alert(EditAddressActivity.this, suggestStr, street2Et);
//			return false;
//		}
		
		city = cityEt.getText().toString().trim();
		if (TextUtils.isEmpty(city)) {
			String suggestStr = getResources().getString(
					R.string.user_address_null, " City ");
			AlertToast.alert(EditAddressActivity.this, suggestStr, cityEt);
			return false;
		}
		state = stateEt.getText().toString().trim();
		if (TextUtils.isEmpty(state)) {
			String suggestStr = getResources().getString(
					R.string.user_address_null, " State ");
			AlertToast.alert(EditAddressActivity.this, suggestStr, stateEt);
			return false;
		}
		country = countryEt.getText().toString().trim();
		if (!"".equals(country) && null != country && null != countryModel) {
			country = (String) MapUtil.getKeyByValue(
					countryModel.getAllCountry(), country).get(0);
		}
		if (TextUtils.isEmpty(country)) {
			String suggestStr = getResources().getString(
					R.string.user_address_null, " Country ");
			AlertToast
					.alert(EditAddressActivity.this, suggestStr, countryEt);
			return false;
		}
		phone = phoneEt.getText().toString().trim();
		if (TextUtils.isEmpty(phone)) {
			String suggestStr = getResources().getString(
					R.string.user_address_null, " Phonenumber ");
			AlertToast.alert(EditAddressActivity.this, suggestStr, phoneEt);
			return false;
		}
		postalCode = postalCodeEt.getText().toString().trim();
		if (TextUtils.isEmpty(postalCode)) {
			String suggestStr = getResources().getString(
					R.string.user_address_null, " PostalCode ");
			AlertToast
					.alert(EditAddressActivity.this, suggestStr, postalCodeEt);
			return false;
		}

		mobile = mobileEt.getText().toString().trim();
		if ("editAddress".equals(fromType)) {
			// setAddressModel(editAddressModel,editAddressModel.getAddress().getIsDefault());
			AddressModel newAddress = getNewAddressModel(editAddressModel,
					false);
			if (newAddress.getAddress().toString()
					.equals(editAddressModel.getAddress().toString())) {
				AlertToast.alert(EditAddressActivity.this,
						getString(R.string.check_address_change));
				return false;
			} else {
				editAddressModel = newAddress;
			}
		} else {
			// setAddressModel(addAddressModel,0);
			addAddressModel = getNewAddressModel(null, true);
		}

		return true;

	}

	/**
	 * 获取请求对象
	 * 
	 * @param addressModel
	 * @param isAddAddress
	 *            是否为新增地址
	 * @return
	 */
	private AddressModel getNewAddressModel(AddressModel addressModel,
			boolean isAddAddress) {
		AddressModel newaddAddressModel = new AddressModel();
		AddressModel.Address address = new AddressModel.Address();
		if (isAddAddress) {
			String customerid = GlobalConfig.getInstance().getUserSessionCfg()
					.getCustomerid();
			if (null == customerid || "".equals(customerid)) {
				customerid = StringUtil
						.getConfig(
								ServerConstant.Parameter.PARAMETER_USER_CUSTOMERID,
								"0");
			}
			long customerId = Long.parseLong(customerid);
			newaddAddressModel.setCustomerID(customerId);
			newaddAddressModel.setAddressType(1);
		} else {
			if (null != addressModel) {
				newaddAddressModel.setAddressID(addressModel.getAddressID());
				newaddAddressModel.setCountryName(country);
				address.setIsDefault(addressModel.getAddress().getIsDefault());
			}
		}
		address.setFirstName(firstName);
		address.setLastName(lastName);
		address.setCountryCode(country);
		address.setState(state);
		address.setCity(city);
		address.setStreet1(street1);
		address.setStreet2(street2);
		address.setPostalCode(postalCode);
		address.setPhoneNumber(phone);
		address.setMobilePhone(mobile);
		newaddAddressModel.setToken(ActivityUtil.getCustomerToken());
		newaddAddressModel.setAddress(address);
		return newaddAddressModel;
	}

	/**
	 * 新增或编辑用户收货地址
	 * 
	 * @author hf
	 * @version [版本号, 2015-8-4]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	class AddOrEditAddress extends BaseNeedReLoginTask {
		private String addressId="";
		@Override
		protected void onPreExecute() {
//			showWaitingDialog();
			showLoadingLayout(null);
			saveBtn.setEnabled(false);
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				Logger.i("AddAddress", "start add " + fromType);
				if ("editAddress".equals(fromType)) {
					editAddressModel.setCustomerID(ActivityUtil.getCustomerID());
					editAddressModel.setToken(ActivityUtil.getCustomerToken());
					ProviderFactory.createUserServiceProvider().UpdateAddress(
							editAddressModel);
				} else {
					addressId=ProviderFactory.createUserServiceProvider().AddAddress(
							addAddressModel);
				}

			} catch (DxException e) {
				return e.getErrCode();
			} catch (Exception e) {
				Logger.e("EditAddressAcitity", "AddOrEditAddress " + fromType,
						e);
			}
			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (!isFinishing()) {
//				hideWaitingDialog();
				hideAllLayout();
				saveBtn.setEnabled(true);
				if ("0".equals(result)) {
					String successStr = "";
					if ("editAddress".equals(fromType)) {
						successStr = getResources().getString(
								R.string.edit_address_success);
						Intent intent = new Intent();
						intent.putExtra("editPosition", editPosition);
						intent.putExtra("addressModel", editAddressModel);
						setResult(ServerConstant.Parameter.EDIT_ADDRESS_CODE,
								intent);
						finish();

					} else {
						successStr = getResources().getString(
								R.string.add_address_success);
						Intent intent = new Intent();
						if(addAddressModel!=null){
							Address address=addAddressModel.getAddress();
							if(null!=address){
								addAddressModel.setCountryName(address.getCountryCode());
							}
							if(null!=addressId&&!"".equals(addressId)){
								addAddressModel.setAddressID(Long.parseLong(addressId));
							}
							
						}
						intent.putExtra("addressModel", addAddressModel);

						setResult(ServerConstant.Parameter.ADD_ADDRESS_CODE,
								intent);
						finish();
					}
					AlertToast.alert(EditAddressActivity.this, successStr);
				} else if(!isRelogin){
					AlertToast.alert(EditAddressActivity.this,
							ServerConstant.ReturnCode.MESSAGEMAP.get(result));
				}
			}
		}

		@Override
		protected Context setContext() {
			return EditAddressActivity.this;
		}

		@Override
		protected BaseNeedReLoginTask setTask() {
			return new AddOrEditAddress();
		}

	}
}
